<template>
  <div class="container">
    <div class="app-container">
      <el-button class="btn-add" size="mini" type="primary" @click="$refs.addPerm.addPermission()">添加路由权限</el-button>
      <el-table default-expand-all :data="list" row-key="id">
        <el-table-column prop="name" label="名称" />
        <el-table-column prop="code" label="标识" />
        <el-table-column prop="description" label="描述" />
        <el-table-column label="操作">
          <template v-slot="{ row }">
            <el-button v-if="row.type === 1" size="mini" type="text" @click="$refs.addPerm.addPermission(row.id, 2)">添加</el-button>
            <el-button size="mini" type="text" @click="$refs.addPerm.editPermission(row.id)">编辑</el-button>
            <el-button size="mini" type="text" @click="deletePermission(row.id)">删除</el-button>
          </template>

        </el-table-column>
      </el-table>
    </div>
    <!-- 添加和编辑权限的弹框 -->
    <AddPermission ref="addPerm" @done="getPermissionPointsList" />
  </div>
</template>
<script>
import { delPermission, getPermissionList } from '@/api/permission'
import { translateListToTree } from '@/utils'
import AddPermission from './AddPermission.vue'

export default {
  name: 'Permission',
  components: {
    AddPermission
  },
  data() {
    return {
      list: []
    }
  },
  created() {
    this.getPermissionPointsList()
  },
  methods: {
    getPermissionPointsList() {
      getPermissionList().then(res => {
        // console.log(res)
        this.list = translateListToTree(res, 0)
      })
    },
    deletePermission(permId) {
      // console.log(permId)
      // Promise中出现的异常会被最近的 catch 所捕获
      this.$confirm('确定要删除当前的权限点吗？')
        .then(() => {
          // console.log('确定要删除')
          return delPermission(permId)
        })
        .then(() => {
          // 提示用户删除成功
          // 重新获取最新的权限数据，并刷新显示
          this.$message.success('权限点删除成功')
          this.getPermissionPointsList()
        })
        .catch(() => {
          console.log('取消删除，点错了')
        })
    }
  }
}
</script>
<style>
.btn-add {
  margin: 10px;
}
</style>
